package comment

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gitee.com/xiaofengfeng123/srv-paper-tape/api/request"
	"gitee.com/xiaofengfeng123/srv-paper-tape/api/response"
	"gitee.com/xiaofengfeng123/srv-paper-tape/database"
	"gitee.com/xiaofengfeng123/srv-paper-tape/errors"
	"gitee.com/xiaofengfeng123/srv-paper-tape/utils"
	"net/http"
	"time"
)

func Route(parentRoute *gin.RouterGroup){
	router := parentRoute.Group("/common")
	router.POST("/add",CommentAdd)
}

func NoAuthRoute(parentRoute *gin.RouterGroup){
	router := parentRoute.Group("/common")
	router.GET("/list",CommentList)
}

func CommentList(c *gin.Context){
	user_id := c.GetString("id")
	id := c.Query("user_id")
	if id != ""{
		user_id = id
	}
	start,offset := request.GetLimit(c)
	cList,total,err := database.CommentListByUid(user_id,start,offset)
	if err !=nil{
		logrus.Errorf("uid: %s ,get commlist error:%s",user_id,cList)
		response.JSON(c,http.StatusInternalServerError,nil,errors.ErrListComment)
		return
	}

	u,b := database.UserByUid(user_id)
	if !b{
		logrus.Errorf("id: %s,get user error:%s",user_id,"用户不存在")
	}

	response.List(c,http.StatusOK,gin.H{
		"list":cList,
		"user_info": u,
	},total,nil)
}

func CommentAdd(c *gin.Context){
	userid := c.GetString("id")


	type Request struct {
		Uid             string       `json:"uid" xorm:"not null 'uid'"`                  //被评论用户id
		Ccontent        string       `json:"ccontent" xorm:"not null 'ccontent'"`           //评论内容
		FromId          string       `json:"from_id"`
	}
	req := new(Request)
	if err := c.ShouldBindJSON(req);err !=nil{
		logrus.Errorf("bind json error:%s\n",err.Error())
		response.JSON(c,http.StatusBadRequest,nil,errors.ErrArg)
		return
	}

	user,err := database.UserById(userid)
	if err !=nil{
		logrus.Errorf("get user erro :%s\n",err.Error())
		response.JSON(c,http.StatusInternalServerError,nil,errors.ErrUserNotFound)
		return
	}

	/*u,err := database.UserById(req.Uid)
	if err ==nil{
		SendMsg(u.Uid,req.FromId,req.Ccontent)
	}*/





	comment := new(database.Comment)
	comment.Uid = req.Uid
	comment.Id = utils.GenUUID()
	comment.Ccontent = req.Ccontent
	comment.Cuid = user.Id
	comment.Uavatar = user.Uavatar
	comment.Uname = user.Uname
	comment.Ctime = time.Now()
	comment.Aname = utils.GenAliasName()

	if err := database.CommentAdd(comment);err !=nil{
		logrus.Errorf("add comment error: %s\n",err.Error())
		response.JSON(c,http.StatusInternalServerError,nil,errors.ErrAddComment)
		return
	}
	response.JSON(c,http.StatusOK,comment,nil)
	return
}

